package com.situ.mall.web.controller;

import com.situ.mall.common.entity.Location;
import com.situ.mall.common.entity.Member;
import com.situ.mall.common.exception.MyException;
import com.situ.mall.common.service.ILocationService;
import com.situ.mall.common.service.IMemberService;
import com.situ.mall.common.util.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author yangkx
 * @create 2023-09-20-10:49
 */
@Controller
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private IMemberService memberService;
    @Autowired
    private ILocationService locationService;

    //打开个人中心
    @GetMapping("/page")
    public String page(Model model){
//        //登陆过，先从session中取出当前登录会员的ID
//        Integer memberId = (int) RequestUtil.getSession().getAttribute("currentId");
//        //再根据memberId去查当前用户的所有信息，转发到页面
//        model.addAttribute("member", memberService.getById(memberId));
        return "personal";
    }

    //修改个人资料
    @GetMapping("/getCurrentMember/{memberId}")
    @ResponseBody
    public Member getCurrentMember(@PathVariable("memberId")Integer id){
        return memberService.selectByMemberId(id);
    }

    //保存个人资料
    @PostMapping("/updateMember")
    @ResponseBody
    public void updateMember(Member member){
        memberService.saveMember(member);
    }


    //注册用户（1.输入手机号）
    @GetMapping("/register")
    public String register(){
        return "register";
    }

    //注册用户（2.带着手机号跳转到注册页面）
    @PostMapping ("/register2")
    public String register2(String tel, Model model){
        //查电话号码长度是不是11位
        if (tel.length() != 11) {
            throw new MyException("电话号码有误，请重新输入");
        }
        //查电话号码是不是0-9纯数字
        for (int i = 0; i < 11; i++) {
            char c = tel.charAt(i);
            if (c < '0' || c > '9') {
                throw new MyException("电话号码有误，请重新输入");
            }
        }
        //查该电话号码有没有被注册
        if (memberService.selectByTel(tel) != null){
            throw new MyException("该电话号码已被注册");
        }
        model.addAttribute("tel",tel);
        return "userRegister";
    }

    //注册用户（3.把全部数据保存进数据库，并跳转到主页）
    @PostMapping("/finalRegister")
    public String finalRegister(String memberName,String password,String tel){
        //1.把用户数据保存进数据库
        memberService.register(memberName,password,tel);
        //2.重定向到主页
        return "redirect:/";
    }

    //添加收货地址
    @PostMapping("/addLocation")
    @ResponseBody
    public void addLocation(Location location){
        //从session中取出当前登录用户的id
        Integer memberId = (int) RequestUtil.getSession().getAttribute("currentId");
        //把会员id放到地址里
        location.setMemberId(memberId);
        //再派service去保存
        locationService.addLocation(location);
    }

}
